package com.wing.purchase.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.product.service.DynamicService;
import com.wing.purchase.dao.PurchaseOrderDao;
import com.wing.purchase.model.entity.*;
import com.wing.purchase.model.entity.PurchaseOrderDetail;
import com.wing.purchase.model.request.PurchaseOrderForm;
import com.wing.purchase.model.response.PurchaseOrderVO;
import com.wing.web.db.config.util.DynamicDataSource;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.wing.purchase.model.entity.PurchaseRequisitions.EnquiryStatus.finish;

/**
 * 采购订单-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class PurchaseOrderServiceImpl extends ServiceImpl<PurchaseOrderDao, PurchaseOrder> implements PurchaseOrderService {

    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private PurchaseOrderDetailService purchaseOrderDetailService;
    @Autowired
    private PurchaseQuotationDetailService purchaseQuotationDetailService;

    @Autowired
    private PurchaseRequisitionsDetailService purchaseRequisitionsDetailService;

    @Autowired
    private PurchaseRequisitionsService purchaseRequisitionsService;

    @Override
    @Transactional(readOnly = false)
    public int add(PurchaseOrderForm purchaseOrderForm) {

        //校验
        PurchaseOrder purchaseOrder = new PurchaseOrder();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(PurchaseOrder.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(purchaseOrderForm, purchaseOrder, copyOptions);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String code = dynamicService.getMaxCode("sn", "pur_purchase_order");
        String day = simpleDateFormat.format(new Date());
        purchaseOrder.setSn("PO" + day + code);
        //供应商联系人
        purchaseOrder.setPersonnelId(purchaseOrderForm.getBusinessContact());
        int i = baseMapper.insert(purchaseOrder);
        if (i > 0) {
            //如果是请购单生成的采购单
            if (purchaseOrderForm.getPurchaseQuotationId() != null) {
                //1. 先保存详情
                Integer codeInt = 0;
                List<PurchaseRequisitionsDetail> details = new ArrayList<>();
                List<PurchaseOrderDetail> orderDetails = new ArrayList<>();
                for (PurchaseOrderDetail purchaseOrderDetail : purchaseOrderForm.getPurchaseOrderDetails()) {
                    purchaseOrderDetail.setCode(String.format("%04d", codeInt += 1));
                    purchaseOrderDetail.setPurchaseOrderId(purchaseOrder.getId());
                    purchaseOrderDetail.setNeedQuantity(purchaseOrderDetail.getQuantity());
                    //已发为0
                    purchaseOrderDetail.setHasDeliveryQuantity(BigDecimal.ZERO);
                    purchaseOrderDetail.setCreateTime(LocalDateTime.now());
                    purchaseOrderDetail.setCreator(JwtUtils.getLoginUserId());
                    purchaseOrderDetail.setCreatorName(JwtUtils.getLoginUsername());
                    orderDetails.add(purchaseOrderDetail);
                    if (purchaseOrderDetail.getQuotationDetailId() != null) {
                        PurchaseRequisitionsDetail byId = purchaseRequisitionsDetailService.getById(purchaseOrderDetail.getQuotationDetailId());
                        if (ObjectUtil.isNotEmpty(byId)) {
                            //原来的剩余数量
                            BigDecimal surplusQuantity = byId.getSurplusQuantity();
                            BigDecimal result = surplusQuantity.subtract(purchaseOrderDetail.getQuantity());
                            byId.setSurplusQuantity(result);
                            details.add(byId);
                        }
                    }
                }
                purchaseOrderDetailService.saveBatch(orderDetails);
                if (CollectionUtil.isNotEmpty(purchaseOrderForm.getQuotationDetailIds())){
                    // 生单成功后修改报价单明细为已生单
                    purchaseQuotationDetailService.updIsGenerateOrder(purchaseOrderForm.getQuotationDetailIds());
                }
                //2. 修改数量
                purchaseRequisitionsDetailService.updateBatchById(details);

                //3. 判断数量sku是否全部生成采购单完毕
                QueryWrapper<PurchaseRequisitionsDetail>  requisitionsDetailQueryWrapper = new QueryWrapper<>();
                requisitionsDetailQueryWrapper.eq("purchase_requisitions_id", purchaseOrderForm.getPurchaseQuotationId());
                requisitionsDetailQueryWrapper.eq("is_deleted",false);
                List<PurchaseRequisitionsDetail> list = this.purchaseRequisitionsDetailService.list(requisitionsDetailQueryWrapper);
                if (CollectionUtil.isNotEmpty(list)) {
                    Boolean isAllOk = true;
                    for (PurchaseRequisitionsDetail purchaseRequisitionsDetail : list) {
                        //剩余发货数 大于 0
                        if (purchaseRequisitionsDetail.getSurplusQuantity().compareTo(BigDecimal.ZERO) > 0) {
                            isAllOk = false;
                        }
                    }
                    if (isAllOk) {
                        PurchaseRequisitions byId = purchaseRequisitionsService.getById(purchaseOrderForm.getPurchaseQuotationId());
                        byId.setEnquiryStatus(finish);
                        byId.setUpdateTime(LocalDateTime.now());
                        purchaseRequisitionsService.updateById(byId);
                    }
                }

            }
            //如果是页面上直接添加的
            else {
                Integer codeInt = 0;
                for (PurchaseOrderDetail purchaseOrderDetail : purchaseOrderForm.getPurchaseOrderDetails()) {
                    purchaseOrderDetail.setCode(String.format("%04d", codeInt += 1));
                    purchaseOrderDetail.setPurchaseOrderId(purchaseOrder.getId());
                    purchaseOrderDetail.setNeedQuantity(purchaseOrderDetail.getQuantity());
//                    purchaseOrderDetail.setHasDeliveryQuantity(purchaseOrderDetail.getQuantity());
                    purchaseOrderDetail.setHasDeliveryQuantity(BigDecimal.ZERO);
                }
                purchaseOrderDetailService.saveBatch(purchaseOrderForm.getPurchaseOrderDetails());
                if (CollectionUtil.isNotEmpty(purchaseOrderForm.getQuotationDetailIds())){
                    // 生单成功后修改报价单明细为已生单
                    purchaseQuotationDetailService.updIsGenerateOrder(purchaseOrderForm.getQuotationDetailIds());
                }
            }
        }
        return i;
    }

    @Override
    @Transactional(readOnly = false)
    public int update(PurchaseOrder purchaseOrder) {
        if (purchaseOrder.getStatus().equals(PurchaseOrder.Status.fail)) {
            // 审核拒绝状态修改之后将状态修改为待审核
            purchaseOrder.setStatus(PurchaseOrder.Status.stayAudit);
        }
        return updateDate(purchaseOrder);
    }


    @Override
    public List<PurchaseOrderVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<PurchaseOrderVO> pageList4app(Page page, Map<String, Object> params) {
        List<PurchaseOrderVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public PurchaseOrderVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional(readOnly = false)
    public int audit(PurchaseOrder purchaseOrder) {
        purchaseOrder.setAuditor(JwtUtils.getLoginUserId());
        return updateDate(purchaseOrder);
    }

    @Override
    public int close(Integer id) {
        PurchaseOrder purchaseOrder = baseMapper.selectById(id);
        purchaseOrder.setStatus(PurchaseOrder.Status.closed);
        return baseMapper.updateById(purchaseOrder);
    }

    @Override
    @Transactional(readOnly = false)
    public boolean delete(Long purchaseOrderId) {
        int i = baseMapper.deleteById(purchaseOrderId);
        if (i > 0) {
            //删除请购单明细
            purchaseOrderDetailService.remove(new QueryWrapper<PurchaseOrderDetail>().eq("purchase_order_id", purchaseOrderId));
        }
        return i > 0;
    }

    @Override
    public PurchaseOrderVO detail(String id) {
        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        return baseMapper.detail(id,databaseUser);
    }

    public int updateDate(PurchaseOrder purchaseOrder) {
        int i = baseMapper.updateById(purchaseOrder);
        if (i > 0) {
            List<PurchaseOrderDetail> addDetails = new ArrayList<>();
            List<PurchaseOrderDetail> updDetails = new ArrayList<>();
            List<Long> delDetails = new ArrayList<>();
            List<Long> ids = new ArrayList<>();
            Integer codeInt = 0;
            for (PurchaseOrderDetail purchaseOrderDetail : purchaseOrder.getPurchaseOrderDetails()) {
                if (null != purchaseOrderDetail.getId()) {
                    ids.add(purchaseOrderDetail.getId());
                }
            }
            // 查询旧数据
            List<PurchaseOrderDetail> oldDetails = purchaseOrderDetailService.list(new QueryWrapper<PurchaseOrderDetail>().eq("purchase_order_id", purchaseOrder.getId()));
            for (PurchaseOrderDetail oldDetail : oldDetails) {
                if (!ids.contains(oldDetail.getId())) {
                    delDetails.add(oldDetail.getId());
                }
            }
            for (PurchaseOrderDetail purchaseOrderDetail : purchaseOrder.getPurchaseOrderDetails()) {
                boolean isRemove = false;
                for (Long id : delDetails) {
                    if (null != purchaseOrderDetail.getId() && id.equals(purchaseOrderDetail.getId())) { // 需要删除的数据
                        isRemove = true;
                    }
                }
                if (!isRemove) {
                    purchaseOrderDetail.setCode(String.format("%04d", codeInt += 1));
                }
                if (null == purchaseOrderDetail.getId()) {
                    purchaseOrderDetail.setCreator(JwtUtils.getLoginUserId());
                    purchaseOrderDetail.setCreatorName(JwtUtils.getLoginUsername());
                    purchaseOrderDetail.setModifier(JwtUtils.getLoginUserId());
                    purchaseOrderDetail.setModifierName(JwtUtils.getLoginUsername());
                    purchaseOrderDetail.setPurchaseOrderId(purchaseOrder.getId());
                    purchaseOrderDetail.setPurchaseOrderId(purchaseOrder.getId());
                    addDetails.add(purchaseOrderDetail);
                } else {
                    ids.add(purchaseOrderDetail.getId());
                    updDetails.add(purchaseOrderDetail);
                }
            }
            if (addDetails.size() > 0) {
                purchaseOrderDetailService.saveBatch(addDetails);
            }
            if (updDetails.size() > 0) {
                purchaseOrderDetailService.updateBatchById(updDetails);
            }
            if (delDetails.size() > 0) {
                purchaseOrderDetailService.removeByIds(delDetails);
            }
        }
        return i;
    }

}
